package cn.wolfcode.controller;

import cn.wolfcode.constant.JwtClaimsConstant;
import cn.wolfcode.pojo.Users;
import cn.wolfcode.properties.JwtProperties;
import cn.wolfcode.result.Result;
import cn.wolfcode.service.UsersService;
import cn.wolfcode.utils.JwtUtil;
import cn.wolfcode.dto.UserRegisterDTO;
import cn.wolfcode.vo.UsersLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.Cookie;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/users")
@Api(tags = "用户")
public class UsersController {
    @Autowired
    UsersService usersService;
    @Autowired
    JwtProperties jwtProperties;


    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public Result<String> userlogin(@RequestBody Users users, HttpServletResponse response){
        Users user = usersService.userLogin(users);
        String password = DigestUtils.md5DigestAsHex(users.getPassword().getBytes());
        if (user == null) {
            return Result.error("用户未注册");
        }else if(!user.getPassword().equals(password)){
            return Result.error("密码错误");
        }
        Map<String,Object> claims = new HashMap();
        claims.put(JwtClaimsConstant.USER_ID,user.getPhone());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        return Result.success("登录成功",token);
    }

    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    public Result userregister(@RequestBody UserRegisterDTO users){
        usersService.userregister(users);
        return Result.success("注册成功");
    }

    @PostMapping("/userinfo")
    @ApiOperation(value = "用户信息")
    public Result<Users> userinfo(HttpServletRequest request) throws Exception {
        Users user = usersService.userinfo(request);
        return Result.success("获取成功",user);
    }
}
